package com.heima.comment.service.impl;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.heima.api.IArticleClient;
import com.heima.api.IAuthClient;
import com.heima.comment.service.CommentService;
import com.heima.comment.user.dtos.ApCommentLikeDto;
import com.heima.comment.user.dtos.ApCommentSaveDto;
import com.heima.comment.user.dtos.ApCommentSearchDto;
import com.heima.comment.user.pojos.ApComment;
import com.heima.comment.user.pojos.ApCommentIsLike;
import com.heima.comment.user.vos.ApCommentSearchVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.CommentThreadLocalUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class CommentServiceImpl implements CommentService {

    private final MongoTemplate mongoTemplate;
    private final IAuthClient iAuthClient;
    private final static Integer DEFAULT_LIKES = 0;
    private final static Integer DEFAULT_REPLY = 0;
    private final static Integer DEFAULT_SIZE = 10;
    private final static Long ABNORMAL_TIME = 20000000000000L;
    private final static Integer LIKE_STATUS = 0;
    private final static Integer UNLOGIN_USERID = 0;


    /**
     * 保存评论
     * @param saveDto
     * @return
     */
    @Override
    public ResponseResult saveComment(ApCommentSaveDto saveDto) {
        //判断用户是否登录
        Integer id = CommentThreadLocalUtil.getUser().getId();
        if(id == UNLOGIN_USERID){
            return ResponseResult.errorResult(AppHttpCodeEnum.USER_UNLOGIN,"用户未登录！");
        }

        //1.将数据拷贝到po中
        ApComment apComment = new ApComment();
        BeanUtils.copyProperties(saveDto,apComment);

        //通过feign请求获取当前用户信息
        String name = iAuthClient.getName(id);

        apComment.setCommentId(UUID.randomUUID().toString());
        apComment.setAuthorId(id);
        apComment.setAuthorName(name);
        long nowTime = System.currentTimeMillis();
        apComment.setCreatedTime(nowTime);
        apComment.setEntryId(saveDto.getArticleId());
        apComment.setLikes(DEFAULT_LIKES);
        apComment.setReply(DEFAULT_REPLY);

        //3.加入数据库
        mongoTemplate.save(apComment);
        return ResponseResult.okResult(null);
    }

    /**
     * 查询评论列表
     * @param searchDto
     * @return
     */
    @Override
    public ResponseResult loadComment(ApCommentSearchDto searchDto) {
        Integer userId = CommentThreadLocalUtil.getUser().getId();
        long minDate = searchDto.getMinDate().getTime();

        Query query = new Query();
        query.addCriteria(Criteria.where("entryId").is(searchDto.getArticleId()));
        if(minDate != ABNORMAL_TIME){
            query.addCriteria(Criteria.where("createdTime").gt(minDate));
        }
        query.limit(DEFAULT_SIZE);
        List<ApComment> commentList = mongoTemplate.find(query, ApComment.class);

        List<ApCommentSearchVo> commentListVos = new ArrayList<>();

        //判断用户是否点赞当前评论
        commentList.stream().map(apComment ->{
            ApCommentSearchVo apCommentSearchVo = new ApCommentSearchVo();
            BeanUtils.copyProperties(apComment,apCommentSearchVo);
            apCommentSearchVo.setId(apComment.getCommentId());
            String id = apComment.getCommentId();
            ApCommentIsLike apCommentIsLike = mongoTemplate.findById(id, ApCommentIsLike.class);

            if(ObjectUtils.isNotEmpty(apCommentIsLike) && userId == apCommentIsLike.getUserId()){
                apCommentSearchVo.setOperation(LIKE_STATUS);
            }
            commentListVos.add(apCommentSearchVo);
            return null;
        }).collect(Collectors.toList());

        return ResponseResult.okResult(commentListVos);
    }

    /**
     * 评论点赞/取消点赞
     * @param likeDto
     * @return
     */
    @Override
    public ResponseResult likeComment(ApCommentLikeDto likeDto) {
        //判断用户是否登录
        Integer id = CommentThreadLocalUtil.getUser().getId();
        if(id == UNLOGIN_USERID){
            return ResponseResult.errorResult(AppHttpCodeEnum.USER_UNLOGIN,"用户未登录！");
        }

        ApComment apComment = mongoTemplate.findById(likeDto.getCommentId(), ApComment.class);
        Integer likes = apComment.getLikes();

        //判断是点赞还是取消
        if(likeDto.getOperation() == LIKE_STATUS){
            //增加点赞数,向ApCommentIsLike表添加数据
            ApCommentIsLike apCommentIsLike = new ApCommentIsLike();
            apCommentIsLike.setUserId(id);
            apCommentIsLike.setCommentId(likeDto.getCommentId()+"");
            mongoTemplate.save(apCommentIsLike);
            //更新ApComment表的点赞数
            likes++;
            apComment.setLikes(likes);
            mongoTemplate.save(apComment);
        }else {
            //取消点赞数,在ApCommentIsLike表删除数据
            mongoTemplate.remove(Query.query(Criteria.where("commentId").is(likeDto.getCommentId())), ApCommentIsLike.class);
            //更新ApComment表的点赞数
            likes--;
            apComment.setLikes(likes);
            mongoTemplate.save(apComment);
        }

        return ResponseResult.okResult(likes);
    }
}
